﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace Core.Framework
{
    public static class AppSetting
    {
        static IConfiguration configuration;

        static AppSetting()
        {
            var framework = "appsettings.json";
#if DEBUG
            framework = "appsettings.debug.json";
#endif

            // 环境变量
            var builder = new ConfigurationBuilder()
                .AddJsonFile(framework, true, true);


            configuration = builder.Build();
        }


        public static bool IsExist(string key)
        {
            return
                !string.IsNullOrWhiteSpace(configuration.GetSection(key)?.Value);
        }

        public static string GetValue(string key)
        {
            return configuration.GetSection(key).Value;
        }

        public static void SetValue(string key, string value)
        {
            configuration.GetSection(key).Value = value;
        }

        public static bool GetValueOfBool(string key)
        {
            return GetValue(key) == "True";
        }

        public static T GetValue<T>(string key)
        {
            var value = JsonConvert.DeserializeObject<T>(GetValue(key));
            return value;
        }

        public static string[] GetArray(string key)
        {
            return configuration
                .GetSection(key).Get<string[]>();
        }


        public static void Bind<T>(T mySettings)
        {
            configuration.Bind(mySettings);
        }

        public static void Bind<T>(string key, T mySettings)
        {
            configuration.GetSection(key).Bind(mySettings);
        }

        public static string GetConnectionString(string key)
        {
            return configuration.GetConnectionString(key);
        }

    }
}
